<template>
  <div>
    <el-form ref="editForm" :model="formItem" label-width="100px" size="mini">
      <div class="anthor">
        <div class="anthor-info">
          <div id="module1">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>基本信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="任务名称">
                    {{ formItem.name }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="计划开始时间">
                    {{ formItem.startTaskTime }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="计划结束时间">
                    {{ formItem.endTaskTime }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领取时间">
                    {{ formItem.getTaskTime }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领取人">
                    {{ formItem.claimName }}
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <div id="module2">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>巡检内容</span></div>
            <div class="anthor-info-body">
              <el-row>
                <el-col v-for="(item,index) in formItem.inspectionTaskProject" :key="index" :span="22" :offset="1">
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>{{ item.locationName+' ： '+item.concreteName }}</span>
                    </div>
                    <el-col v-for="(it, ind) in item.itemValue" :key="`${index-ind}`" :span="8">
                      <el-form-item v-if="it.valueType==='string'" :label="`${it.name+'(字符型)'}`" :title="`${'告警范围：'+it.ruleItem.alarm+'；预警范围：'+it.ruleItem.earlyWarning}`">
                        <el-input v-model="it.value" placeholder="请输入值" :maxlength="255" />
                      </el-form-item>
                      <el-form-item v-else :label="`${it.name+'(数值型)'}`" :title="`${'告警值下限：'+it.ruleItem.alarmDown+'；预警值下限：'+it.ruleItem.earlyWarningDown + '；预警值上限：'+it.ruleItem.earlyWarningUpper+'；告警值上限：'+it.ruleItem.alarmUpper}`">
                        <el-input v-model="it.value" placeholder="请输入值" :maxlength="255" />
                      </el-form-item>
                    </el-col>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>

          <div id="module3">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>附加信息</span></div>
            <div class="anthor-info-body">
              <el-form-item label="备注" title="如是补录，则此项必填">
                <el-input v-model="formItem.note" :maxlength="1023" type="textarea" :rows="2" :autosize="true" resize="none" />
              </el-form-item>
            </div>
          </div>
          <anchor key="el-dialog__body" :xleft="1" :ytop="10" container=".el-dialog__body" :title-list="anchorList" />
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { list } from '@neu/dcom-ui/api/functional'
import { update, detail, submit } from '@neu/dcom-ui/api/inspectionTask'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import Anchor from '@neu/biz-core/components/Anchor/index'
import { formatDate } from '@neu/biz-core/utils/utils'

// 定义一个表单原始项
const formItem = {
  name: '',
  // 计划结束时间
  endTaskTime: '',
  // 计划开始时间
  startTaskTime: '',
  // 领取任务时间
  getTaskTime: '',
  // 巡检内容
  inspectionTaskProject: [],
  // 备注
  note: ''
}
export default {
  name: 'InspectionRuleEdit',
  components: {
    Anchor
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** 巡检对象类型 */
      projectTypes: [],
      anchorList: [ // 锚点列表
        { id: 'module1', label: '基本信息' },
        { id: 'module2', label: '巡检内容' },
        { id: 'module3', label: '附加信息' }
      ],
      /** 巡检类型（职能） */
      inspectionTypes: [],
      /** 超时设置**/
      overTime: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    list().then(response => {
      this.inspectionTypes = response.data
    })
    findByDictionaryType('projectType').then(response => {
      this.projectTypes = response.data
    })
    findByDictionaryType('inspectionOverTime').then(response => {
      this.overTime = response.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
          this.formItem.endTaskTime = formatDate(this.formItem.endTaskTime)
          this.formItem.startTaskTime = formatDate(this.formItem.startTaskTime)
          this.formItem.getTaskTime = formatDate(this.formItem.getTaskTime)
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          // if (valid) {
          let flag = false
          let msg = ''
          for (const i in this.formItem.inspectionTaskProject) {
            const t = this.formItem.inspectionTaskProject[i]
            for (const j in t.itemValue) {
              const item = t.itemValue[j]
              if (item.valueType === 'number' && item.value && isNaN(Number(item.value))) {
                flag = true
                msg = t.concreteName + '的' + item.name + ' 的值应该为数值型'
                break
              }
            }
          }
          if (flag) {
            return this.$message({
              showClose: true,
              message: msg,
              type: 'error'
            })
          }
          // const endTime = Number(new Date(this.formItem.endTaskTime))
          // const currentTime = Number(new Date())
          // let difference = 24 * 3600 * 1000// 默认为24小时
          // if (this.overTime && this.overTime.length > 0 && !isNaN(Number(this.overTime[0].text))) {
          //   debugger
          //   difference = Number(this.overTime[0].text) * 3600 * 1000
          // }
          // if ((currentTime - endTime) > difference) {
          //   if (!this.formItem.note) {
          //     return this.$message({
          //       showClose: true,
          //       message: '已超出计划结束时间24小时，必须填写备注',
          //       type: 'error'
          //     })
          //   }
          //   this.formItem.status = 'overtimeUnfinished'
          // }

          if (updated) {
            resolve(update(this.id, this.formItem))
          } else {
            // resolve(create(this.formItem))
          }
          // } else {
          //   resolve(false)
          // }
        })
      })
    },
    submit() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          // if (valid) {
          let flag = false
          let msg = ''
          for (const i in this.formItem.inspectionTaskProject) {
            const t = this.formItem.inspectionTaskProject[i]
            for (const j in t.itemValue) {
              const item = t.itemValue[j]
              if (item.valueType === 'number' && item.value && isNaN(Number(item.value))) {
                flag = true
                msg = t.concreteName + '的' + item.name + ' 的值应该为数值型'
                break
              }
            }
          }
          if (flag) {
            return this.$message({
              showClose: true,
              message: msg,
              type: 'error'
            })
          }
          const endTime = Number(new Date(this.formItem.endTaskTime))
          const currentTime = Number(new Date())
          let difference = 24 * 3600 * 1000// 默认为24小时
          if (this.overTime && this.overTime.length > 0 && !isNaN(Number(this.overTime[0].text))) {
            debugger
            difference = Number(this.overTime[0].text) * 3600 * 1000
          }
          if ((currentTime - endTime) > difference) {
            if (!this.formItem.note) {
              return this.$message({
                showClose: true,
                message: '已超出计划结束时间24小时，必须填写备注',
                type: 'error'
              })
            }
            this.formItem.status = 'overtimeUnfinished'
          }

          if (updated) {
            resolve(submit(this.id, this.formItem))
          } else {
            // resolve(create(this.formItem))
          }
          // } else {
          //   resolve(false)
          // }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
    },
    ok() {
      this.$refs.editProjectForm.save()
    }

  }
}
</script>
